﻿using System;

namespace Hsenl.Network {
    public class TcpPacketReceiver : APacketHandler, IPacketReceiver, IMessageReader {
        private const int BodySizeBits = 2;
        private const int TotalHeadBits = 2;

        private readonly PacketReader _packetReader = new();

        public event Action<Memory<byte>> OnMessageReadedEvent {
            add => this._packetReader.OnMessageReadedEvent += value;
            remove => this._packetReader.OnMessageReadedEvent -= value;
        }

        protected override void OnInit(Channel channel) {
            this._packetReader.Init(BodySizeBits, TotalHeadBits);
        }

        public byte[] GetRecvBuffer(int len, out int offset, out int count) {
            return this._packetReader.GetRecvBuffer(len, out offset, out count);
        }

        public Memory<byte> GetRecvBuffer(int length) {
            return this._packetReader.GetRecvBuffer(length);
        }

        public void Read(Memory<byte> data) {
            this._packetReader.Read(data);
        }

        protected override void OnDisposed() {
            this._packetReader.Dispose();
        }
    }
}